package com.thoughtservice.jspdoc.processors;


import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtservice.jspdoc.JSPFileList;
import com.thoughtservice.jspdoc.JSPPage;
import com.thoughtservice.jspdoc.RE;
import com.thoughtservice.jspdoc.RESyntaxException;
import com.thoughtservice.jspdoc.utils.ProcessorUtils;

public class ProcessRedirects implements DocProcessor{

	private final static Logger LOG = LoggerFactory.getLogger(ProcessRedirects.class);
	 
	public boolean process(JSPPage p, String pc, JSPFileList fileList)
			throws RESyntaxException {
		LOG.trace("Entering {}", "ProcessRedirects");
		RE re;
		int index;
		// Look for Redirects
		re = new RE("response.sendRedirect\\([:print:]*\\);");
		index = 0;
		while (re.match(pc, index)) {
			//			System.out.println(re.getParen(0));
			String link = re.getParen(0);
			index = re.getParenEnd(0);
			RE re2 = new RE("\\([:print:]*\\);");
			re2.match(link);
			link = re2.getParen(0);
			link = link.substring(1, link.length() - 2);
			try {
				// Try to work out a text based link if possible
				ProcessorUtils.figureLink(link, p, JSPPage.REDIRECTS);
			} catch (Exception e) {
				// If an error occurs then just do nothing
				LOG.error("An exception occured and i am recovering {}", ExceptionUtils.getFullStackTrace(e));
			}
		}
		LOG.trace("Exiting {}", "ProcessRedirects");
	
		return false;
	}
}
